package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.web-site}")
    String webSite;
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验，判断上传的文件格式是否正确
        if (multipartFile == null || multipartFile.getSize() == 0) {

            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传有效文件");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 获取原始文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        // 2 上传到oss
        //获取原始文件后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //新文件名称：随机生成UUID再加上获取的后缀
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //新的文件名称=随机生成的uuid+substring
        String newFilename = uuid + substring;
        //调用上传方法
        try {
            String store = fileStorageService.store(prefix, newFilename, multipartFile.getInputStream());
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(store);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());
            // 保存素材
            save(wmMaterial);
            // 4 返回结果，需要在url上加访问前缀
            wmMaterial.setUrl(webSite + wmMaterial.getUrl());
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("服务器异常，文件上传失败===>{}", e.getMessage());
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        // 创建NMaterial实体类对象




        /**
         * 检查文件格式
         * @param path
         * @return
         */
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1校验参数
        dto.checkParam();
        //验证用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 封装查询参数
        IPage<WmMaterial> pageReq = new Page<>(dto.getPage(), dto.getSize());
        // 2.1 分页参数
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (dto.getIsCollection() != null && dto.getIsCollection().intValue() == 1) {
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, WemediaConstants.COLLECT_MATERIAL);
        }
        lambdaQueryWrapper.eq(WmMaterial::getUserId, user.getId());
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //封装数据
        IPage<WmMaterial> pageResult = page(pageReq, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        responseResult.setData(records);
        return responseResult;

    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult deletePicture(Integer id) {
        //检验参数
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 查询该素材是否被引用   id  素材id   文章id
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getId, id));
        if (count>0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "该素材已被引用，无法进行此操作");
        }
// 3. 查询素材信息  ==> url (oss路径)
        WmMaterial wmMaterial = getById(id);
        //检索素材信息是否为空
        if (wmMaterial==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 4. 删除对应oss文件
        String url = wmMaterial.getUrl();
        fileStorageService.delete(url);
        // 5. 删除素材数据
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //检索数据是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, type)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, user.getId())
        );
        return ResponseResult.okResult();
    }
}
